package com.doerit.laptops.util;

import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.doerit.laptops.exception.EmailSendException;

public class EmailRequest extends AbstractEmailSend implements EmailSend {


    public void sendEmail(final Map<String, String> params, final String templateName) throws Exception {

        if (params.get(EMAIL).indexOf("@") > 0) {

            MimeMessagePreparator preparator = new MimeMessagePreparator() {
                public void prepare(MimeMessage mimeMessage) throws Exception {

                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                    mimeMessage.setDisposition("inline");

                    mimeMessage.setHeader("Content-Transfer-Encoding", "8bit");

                    mimeMessage.setHeader("Content-Type", "Text/HTML;\tcharset=ISO-2022-JP");
                    mimeMessage.setSubject(params.get(EMAIL_SUBJECT), "UTF-8");
                    message.setTo(params.get(EMAIL));
                    message.setFrom(senderEmail);

                    Map<String, Object> model = new HashMap<String, Object>();
                    
                    if(params.get(PASSWORD) != null){
                    	model.put("password", params.get(PASSWORD));
                    }
                   
                    String text = "";

                    text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                             		"com/aios/util/".concat(templateName), "UTF-8", model);

                    mimeMessage.setText(text, "UTF-8");

                }
            };
            
            try {
            	this.mailSender.send(preparator);
            } catch (RuntimeException e) {
            	throw new EmailSendException("Due to invalid email address, mail cannot be send.");
			} catch (Exception ex) {
            	ex.printStackTrace();
            }
        } else {
            logger.info("Email not sending due to invalid email address " + params.get(EMAIL));
        }

    }

    public String removeHtml(String text){
		text = text.replaceAll("\\<.*?>","");
		text = text.replaceAll("&nbsp;","");
		text = text.replaceAll("&amp;","");
	 return text;
	}

}
